import React, { Component } from 'react'

export default class LianXi extends Component {

    state = {
        list: [
            { id: 1, title: '草莓', price: 6, sed: false },
            { id: 2, title: '苹果', price: 2, sed: true },
        ],
        title: ''
    }

    //添加的方法
    add = () => {
        let obj = {
            id: new Date().getTime(),
            title: this.state.title,
            price: 7,
            sed: false
        }
        this.setState({ list: [...this.state.list, obj] })
    }

    //删除的方法
    del = (id) => {
        let newlist = this.state.list.filter(item => {
            return item.id !== id
        })
        this.setState({ list: newlist })
    }

    //状态切换的方法
    changeSed = (id) => {
        let newlist = [...this.state.list]
        newlist.forEach(item => {
            if (item.id == id) {
                return item.sed = !item.sed
            }
        })
        this.setState({ list: newlist })
    }

    render() {
        let { list, title } = this.state
        return (
            <div>
                {/* 添加 */}
                <input value={title} onChange={(e) => {
                    this.setState({ title: e.target.value })
                }} />
                <button onClick={this.add}>添加</button>
                {/* 渲染到页面上 */}
                <div>
                    {
                        list.map(item => {
                            return <div key={item.id}>
                                <span>名称:{item.title}</span>
                                <span>价格:{item.price}</span>
                                <button onClick={() => {
                                    this.changeSed(item.id)
                                }}>{item.sed ? '上架' : '下架'}</button>
                                <button onClick={() => {
                                    this.del(item.id)
                                }}>删除</button>
                            </div>
                        })
                    }
                </div>
            </div>
        )
    }
}
